package com.qqt.csr.order.service.statemachine.action.impl;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.qqt.csr.common.acl.aics.AICustomerServiceClient;
import com.qqt.csr.common.acl.aics.resp.CsMemberInfoDTO;
import com.qqt.csr.message.event.intrasite.IntraSiteMessageEventPublisher;
import com.qqt.csr.message.event.intrasite.workorder.WorkOrderEventSource;
import com.qqt.csr.order.entity.WorkOrder;
import com.qqt.csr.order.enums.WorkOrderEventEnum;
import com.qqt.csr.order.enums.WorkOrderStatusEnum;
import com.qqt.csr.order.enums.WorkOrderTemplateType;
import com.qqt.csr.order.service.event.DynamicEvent;
import com.qqt.csr.order.service.event.DynamicEventListener;
import com.qqt.csr.order.service.event.DynamicEventSource;
import com.qqt.csr.order.service.statemachine.action.IActionPostProcessor;
import com.qqt.csr.order.service.statemachine.action.IActionPreProcessor;
import com.qqt.csr.order.service.statemachine.context.WorkOrderContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UpdatedDesigneeWorkOrderProcessor extends AbstractWorkOrderProcessor implements IActionPreProcessor, IActionPostProcessor {
    @Autowired
    private IntraSiteMessageEventPublisher messageEventPublisher;
    @Autowired
    private DynamicEventListener dynamicEventListener;
    @Autowired
    private AICustomerServiceClient customerServiceClient;

    @Override
    public boolean matches(WorkOrderEventEnum event) {
        return WorkOrderEventEnum.UPDATED_DESIGNEE.equals(event);
    }

    @Override
    public void preProcess(WorkOrderStatusEnum from, WorkOrderStatusEnum to, WorkOrderEventEnum event, WorkOrderContext context) {
        JSONObject ext = new JSONObject();
        ext.put("designeeId", context.getToOrder().getDesigneeId());
        context.setEventExt(ext);
    }

    @Override
    public void postProcess(WorkOrderStatusEnum from, WorkOrderStatusEnum to, WorkOrderEventEnum event, WorkOrderContext context) {
        if(context.getFromOrder().isNeedSysNotify()){
            sendMsgNotify(context);
        }

        recordDynamic(context, event);
    }

    /**
     * 推送系统通知
     * 需要通知的人：
     * A创建，A处理人->A变更为B处理人，通知：B（新处理人）
     * A创建，B处理人->A变更为C处理人，通知：B（原处理人）、C（新处理人）
     * A创建，B处理人->B变更为C处理人，通知：A（创建人）、C（新处理人）
     * A创建，B处理人->B变更A处理人，通知：A（新处理人、创建人）
     *
     * @param context
     */
    private void sendMsgNotify(WorkOrderContext context) {
        WorkOrder toOrder = context.getToOrder();
        WorkOrder fromOrder = context.getFromOrder();
        if (toOrder.getDesigneeId().equals(fromOrder.getDesigneeId())) {
            return;
        }

        List<WorkOrderEventSource> msgNotifyList = new ArrayList<>();
        if (!toOrder.getDesigneeId().equals(context.getOperatorId())) {
            // 通知新处理人
            msgNotifyList.add(new WorkOrderEventSource()
                    .setWorkOrderId(fromOrder.getId())
                    .setWorkOrderName(fromOrder.getTitle())
                    .setEventType(WorkOrderTemplateType.SET_UP_PROCESSOR)
                    .setParams(new String[]{context.getOperatorName()})
                    .setLinkUrl(StringUtils.EMPTY)
                    .setExt("{\"permission\":\""+ORDER_PROCESSOR_PERM+"\"}")
                    .setRecipientIds(Lists.newArrayList(toOrder.getDesigneeId())));
        }

        if (!fromOrder.getCreatorId().equals(context.getOperatorId())) {
            // 通知创建人
            msgNotifyList.add(new WorkOrderEventSource()
                    .setWorkOrderId(fromOrder.getId())
                    .setWorkOrderName(fromOrder.getTitle())
                    .setEventType(WorkOrderTemplateType.CHANGE_PROCESSOR_PERMISSION)
                    .setParams(new String[]{context.getOperatorName()})
                    .setLinkUrl(StringUtils.EMPTY)
                    .setExt("{\"permission\":\""+ORDER_CREATOR_PERM+"\"}")
                    .setRecipientIds(Lists.newArrayList(fromOrder.getCreatorId())));
        }

        if (context.getOperatorId().equals(fromOrder.getCreatorId())
                && fromOrder.isAllocated()
                && !fromOrder.getCreatorId().equals(fromOrder.getDesigneeId())) {
            // 通知原处理人
            msgNotifyList.add(new WorkOrderEventSource()
                    .setWorkOrderId(fromOrder.getId())
                    .setWorkOrderName(fromOrder.getTitle())
                    .setEventType(WorkOrderTemplateType.CHANGE_PROCESSOR_PERMISSION)
                    .setParams(new String[]{context.getOperatorName()})
                    .setLinkUrl(StringUtils.EMPTY)
                    .setExt("{\"permission\":\""+ORDER_POOL_PERM+"\"}")
                    .setRecipientIds(Lists.newArrayList(fromOrder.getDesigneeId())));
        }

        msgNotifyList.forEach(msgNotify -> {
            messageEventPublisher.publishEvent(msgNotify);
        });
    }

    /**
     * 记录动态
     *
     * @param context
     */
    private void recordDynamic(WorkOrderContext context, WorkOrderEventEnum event) {
        List<CsMemberInfoDTO> csMemberInfoDTOList = customerServiceClient.getNormalListBy(Lists.newArrayList(context.getToOrder().getDesigneeId()));
        String processorName = csMemberInfoDTOList.stream().map(CsMemberInfoDTO::getNickName).findFirst().orElse(StringUtils.EMPTY);

        DynamicEventSource eventSource = new DynamicEventSource()
                .setEvent(event)
                .setReasonForAssignment(context.getToOrder().getAllocateCause())
                .setOrderId(context.getToOrder().getId())
                .setProcessor(processorName);
        dynamicEventListener.onApplicationEvent(new DynamicEvent(eventSource));
    }


}
